﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;

namespace CWCS.Core.Library.SocketManager
{
    public delegate void DNotifyMessage(string Command, object Mesg);

    public class SocketServer
    {
        //事件
        public event DNotifyMessage NotifyEventHanlder;

        private IPEndPoint myServer;
        private Socket sock;
        private Socket accsock;
        private bool bAccp = true;
        private bool bRound = true;
        Thread thread;
        Thread thread2;

        private int _nIpPort;
        private string _strIpAddress;

        public SocketServer(string ipaddress, int ipport)
        {
            _strIpAddress = ipaddress;
            _nIpPort = ipport;
        }

        public void StartListening()
        {
            try
            {
                thread = new Thread(new ThreadStart(accp)); //生成监听线程；
                thread.IsBackground = false;//主线程关闭则辅线程自动关闭
                thread.Start();
            }
            catch (Exception ex)
            {
                ONNotifyEventHanlder("Break", "无法监听:" + ex.Message);
            }
        }

        private void accp()
        {
            //myServer = new IPEndPoint(IPAddress.Any, _nIpPort);
            IPAddress ipAddress = IPAddress.Parse(_strIpAddress);
            IPEndPoint myServer = new IPEndPoint(ipAddress, _nIpPort);//监听指定IP地址
            sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            try
            {
                sock.Bind(myServer);
                ONNotifyEventHanlder("Listen", "主机:" + _strIpAddress + " 端口:" + _nIpPort.ToString() + " 开始监听！");
                sock.Listen(50);
                while (bAccp)
                {
                    try
                    {
                        var accsock1 = sock.Accept();
                        bRound = false;
                        thread2?.Join();
                        accsock?.Close();
                        accsock?.Dispose();
                        accsock = accsock1;
                        if (accsock.Connected)
                        {
                            ONNotifyEventHanlder("Connect", "主机:" + _strIpAddress + " 端口:" + _nIpPort.ToString() + " 与客户建立连接！");
                            thread2 = new Thread(new ThreadStart(round)) { IsBackground = true };//如果有客户请求，生成与客户通信的线程。
                            thread2.Start();
                            bRound = true;
                        }
                        else
                        {
                            ONNotifyEventHanlder("Break", "连接断开");
                        }
                    }
                    catch (Exception ex)
                    {
                        ONNotifyEventHanlder("Break", "主机:" + _strIpAddress + " 端口:" + _nIpPort.ToString() + "监听异常1:" + ex.Message);
                    }
                }
            }
            catch (Exception ex)
            {
                ONNotifyEventHanlder("Break", "主机:" + _strIpAddress + " 端口:" + _nIpPort.ToString() + "监听异常2:" + ex.Message);
            }
        }

        private void round()
        {
            Byte[] recBuff = null;
            string strbuff = null;

            while (bRound)
            {
                try
                {
                    if (accsock.Connected)
                    {
                        NetworkStream netStream = new NetworkStream(accsock);

                        recBuff = new byte[1000];
                        netStream.Read(recBuff, 0, recBuff.Length);//读取客户发送来的信息。

                        strbuff = System.Text.Encoding.ASCII.GetString(recBuff, 0, recBuff.Length).Trim('\0');
                        if (strbuff.Length > 0)
                        {
                            ONNotifyEventHanlder("RecvData", strbuff);
                            netStream.Close();
                            System.Threading.Thread.Sleep(1000);
                        }
                        else
                        {
                            ONNotifyEventHanlder("Listen1", strbuff);
                        }
                    }
                    else
                    {
                        bRound = false;
                        ONNotifyEventHanlder("Listen", "主机:" + _strIpAddress + " 端口:" + _nIpPort.ToString() + " 开始监听！");
                    }
                    //ONNotifyEventHanlder("RecvData", strbuff);
                }
                catch (Exception ex)
                {
                    ONNotifyEventHanlder("Listen", "主机:" + _strIpAddress + " 端口:" + _nIpPort.ToString() + " 开始监听！！");
                    //ONNotifyEventHanlder("Listen", "主机:" + _strIpAddress + " 端口:" + _nIpPort.ToString() + "获取数据异常:" + ex.Message + ex.StackTrace + ex.Source + ex.TargetSite);
                    bRound = false;
                }
            }
        }

        public void SendMessage(byte[] sendbyte)
        {
            try
            {
                NetworkStream netStream = new NetworkStream(accsock);//生成NetworkStream实例，用于发送基础数据流。
                netStream.Write(sendbyte, 0, sendbyte.Length);
                netStream.Close();
            }
            catch (Exception ex)
            {
                ONNotifyEventHanlder("SendData", "主机:" + _strIpAddress + " 端口:" + _nIpPort.ToString() + "发送数据异常:" + ex.Message);
            }
        }

        public void ONNotifyEventHanlder(string Command, object Mesg)//事件函数
        {
            if (NotifyEventHanlder != null)
                NotifyEventHanlder(Command, Mesg);
        }
    }
}
